package ce.service;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import net.bat.db.BaseDAO;
import net.bat.db.BaseDAOImpl;
import net.bat.util.Cfg;
import net.bat.util.Encrypt;

import org.hibernate.EntityMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;

//import avens.AvensEngineManager;
//import avens.common.AvensConstants;
//import avens.omgapi.WorkflowModel.WfResource;
//import dao.hb.AvensOrg;
//import dao.hb.AvensResource;
import dao.hb.AvensOrg;
import dao.hb.UUser;

/**
 * @author Administrator
 * 
 *         更改所生成类型注释的模板为 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
public class SinosoftUM {

	private static BaseDAOImpl dao = (BaseDAOImpl) Cfg.getBean("BaseDAOImpl");

	static public String getpersonfromURL(String getpropertyurl)
			throws MalformedURLException {
		URL u = new URL(getpropertyurl);
		String s = null;
		BufferedReader r = null;
		try {
			URLConnection uc = u.openConnection();
			uc.setRequestProperty("Connection", "close");
			try {
				r = new BufferedReader(new InputStreamReader(
						uc.getInputStream()));
			} catch (Exception ex) {
				System.out.println("读流出错：" + ex);
			}
			String line;
			StringBuffer buf = new StringBuffer();
			while ((line = r.readLine()) != null)
				buf.append(line);
			s = buf.toString();
		} catch (Exception ex1) {
			System.out.println("读流出错：" + ex1);
		} finally {
			try {
				r.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return s;
	}

	static public String getAllpersonfromLdap() {

		String userstr = null;
		//String orgId = AvensConstants.BaseDN.replaceAll("=", "%3D");
		String orgId = Cfg.BaseDN.replaceAll("=", "%3D");  //orgId : dc%3Dgugong
		
		// String
		// urlstring=AvensConstants.UmHome+"queryldapbin1?objectclass=guGongPerson&basedn="+orgId+"&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;&attrname=description";
		//String urlstring = AvensConstants.UmHome   //wjh
		String urlstring = Cfg.UmHome
				+ "queryldapbin1?objectclass=guGongPerson&basedn="
				+ orgId
				+ "&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;&attrname=description,mobilePhone,guGongDuty&personstatus=all";  //guGongTitle->guGongDuty
		try {
			userstr = getpersonfromURL(urlstring);//http://192.168.1.45:8088/um/queryldapbin1?objectclass=guGongPerson&basedn=dc%3Dgugong&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;&attrname=description,mobilePhone,guGongTitle&personstatus=all
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return userstr;  //cn=admin,dc=gugong:系统管理员::;cn=110105520713581,ou=ziliaoxin
		// savetodb(userstr);

	}

//	public String getpersonsfromLdapbyorg(String orgID) {
//
//		String userstr = null;
//		String orgId = "ou%3D" + orgID;
//		String urlstring = AvensConstants.UmHome
//				+ "queryldapbin1?objectclass=guGongPerson&basedn="
//				+ orgId
//				+ "&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;&attrname=description";
//		try {
//			userstr = getpersonfromURL(urlstring);
//		} catch (MalformedURLException e) {
//			e.printStackTrace();
//		}
//		return userstr;
//	}
//
	static private boolean isSame(String v1, String v2) {
		if (v1 == null)
			v1 = "";
		if (v2 == null)
			v2 = "";
		return v1.equals(v2);
	}

	static public String getOrgFromUserdn(Session s,String userdn){
		String org="";
		//去掉cn
		if (userdn.indexOf("cn=") == 0) {
			int ipos = userdn.indexOf(",");
			if (ipos > 0) {
				userdn = userdn.substring(ipos + 1);
			}
		}
		//org表查
		try {
			AvensOrg robj;
			String strHQL = "From AvensOrg Where orgid=:userdn";             // Userdn:"cn=110102641211331,ou=jinshizu,ou=guqiwubu,dc=gugong
			robj = (AvensOrg) s.createQuery(strHQL).setString("userdn", userdn).uniqueResult();
			if (robj != null){
				org = robj.getOrgname();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return org;
	}
	//同步组织机构人员
	static public String savetodb(String userstr,String orgstr) {
		String cn = "dao.hb.UUser";
		//String cn = "dao.hb.AvensResource";
		//String cn2 = "dao.hb.AvensOrg";
		SessionFactory sf = dao.getSessionFactory();//wjh 
		//SessionFactory sf = getDao().currentSessionFactory();//wjh
		Session s = sf.openSession();
		ClassMetadata cm = dao.getClassMeta(cn);
		//ClassMetadata cm2 = dBHelper.getClassMeta(cn2);
		//ClassMetadata cm = getDao().getClassMeta(cn);
		//ClassMetadata cm2 = getDao().getClassMeta(cn2);
		
		String[] sp = null;
		sp = userstr.split(";");
		int cout1 = 0;
		int cout2 = 0;
		// 同步用户信息
		for (int i = 0; i < sp.length; i++) {
			String[] uinf = new String[4];
			int lastPos = -1;
			int pos = -1;
			for (int j = 0; j < 4; j++) {
				lastPos = pos;
				pos = sp[i].indexOf(':', pos + 1);
				if (pos == -1) {
					uinf[j] = sp[i].substring(lastPos + 1);
					break;
				} else {
					uinf[j] = sp[i].substring(lastPos + 1, pos);
				}
			}
			String userdn = uinf[0]; //cn=110102641211331,ou=jinshizu,ou=guqiwubu,dc=gugong
			String org = getOrgFromUserdn(s,userdn);
			int pos2 = userdn.indexOf(',');
			String username;
			if (pos2 > 0)
				username = userdn.substring(0, pos2);
			else
				username = userdn;                  //cn=110102641211331
			String name = uinf[1];                //李和惠
			name = "[" +org+ "]" + name;
			//String title = uinf[3];     //职称
			String duty = uinf[3];         //主任....,处长..馆长 ,所长,guGongDuty

			boolean bSave = true;
			UUser robj;
			boolean updateUser=false;
			try {
				String strHQL = "From UUser Where userId=:userId"; 						
				robj = (UUser)s.createQuery(strHQL).setString("userId",username).uniqueResult();  						
				//robj = (UUser) s.get(cn, username);  //cn:"dao.hb.UUser";  username:cn=110102641211331
				if ((robj!=null) && isSame(name, robj.getName()) 
						&& isSame(username, robj.getUserId())
						//&& isSame(duty, robj.getDuty())
						//&& isSame(title, robj.getTitle())
						//&& isSame(userdn, robj.getUserdn())
						){               //找到 ,信息一致   name 李米佳 , Title "" ,Userdn:"cn=110102641211331,ou=jinshizu,ou=guqiwubu,dc=gugong"
					bSave = false;
				}else if ((robj!=null)){  //找到 ,信息不一致
					updateUser=true;
				}else{  //没有找到
					robj = (UUser) cm.instantiate(null, EntityMode.POJO);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				robj = (UUser) cm.instantiate(null, EntityMode.POJO);
			}
			if (bSave) {
				robj.setName(name);
				robj.setUserId(username);//cn=110102641211331
				       // 资料信息中心 cn=110102641211331,ou=jinshizu,ou=guqiwubu,dc=gugong
			
				String pwd="1";
				String pwd_ept = Encrypt.calcUserEncrypt(username, pwd);  
				robj.setPwd(pwd_ept);  //11111
				/*
				robj.setUid(1);
				robj.setDuty(duty);
				robj.setOrg(org); 
				*/ //fucj 
				Date dt = new Date();
				if (updateUser){      //更新
					robj.setDtModify(dt);
				}else{
					robj.setDtCreate(dt);
					robj.setGid(0);//组
				}
				
				//robj.setUserdn(userdn);
				//robj.setTitle(title);
				//String org = "";
//				int cpos = userdn.indexOf(',');
//				if (cpos != -1)
//					org = userdn.substring(cpos + 1);
				//robj.setOrg(org);
				// robj.setPassword("111111");
//				int ver = 1;
//				Integer version = robj.getVersion();
//				if (version != null)
//					ver = version++;
//				robj.setVersion(ver);
				s.save(robj);
				
//boolean devdebug=true;				
//System.out.println("=======savetodb========"+i+",updateUser:"+updateUser+",name:"+name+",username:"+username);	
//
//if (devdebug && (i>20)){
//	break;
//}
				cout1++;
			}
		}

		// 同步组织机构信息
		/*sp = orgstr.split(";");
		for (int i = 0; i < sp.length; i++) {
			String[] sps = sp[i].split(":");
			String orgname = sps[1];
			String orgid = sps[0];
			String orgord = null;
			if (sps.length > 2)
				orgord = sps[2];
			int pos = orgid.indexOf(",");
			String oid = orgid;
			String pid = orgid.substring(pos + 1);
			boolean bSave = true;
			AvensOrg robj;
			try {
				robj = (AvensOrg) s.get(cn2, oid);
				String oldord = robj.getOrd() == null ? null : robj.getOrd()
						.toString();
				if (isSame(orgname, robj.getOrgname())
						&& isSame(pid, robj.getParentorgid())
						&& isSame(orgord, oldord))
					bSave = false;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				robj = (AvensOrg) cm2.instantiate(null, EntityMode.POJO);
			}
			if (bSave) {
				robj.setOrgname(orgname);
				robj.setParentorgid(pid);
				robj.setOrgid(oid);
				int ord = 0;
				if (orgord != null && !orgord.equals("")) {
					ord = Integer.parseInt(orgord);
					robj.setOrd(ord);
				}
				int ver = 1;
				Integer version = robj.getVersion();
				if (version != null)
					ver = version++;
				robj.setVersion(ver);
				s.save(robj);
				cout2++;
			}
		}*/

		s.flush();
		s.close();
		//return "更新人员：" + cout1 + "条，更新组织机构:" + cout2 + "条";
		return "更新人员：" + cout1 + "条";
	}
//
//	/*
//	 * type=zhengchuzhang 正处长 type=zhengkezhang 正科长
//	 */
//	public String getDeptleaderfromLdap(String orgID, String type) {
//		String orgid = "ou%3D" + orgID;
//		//AvensConstants.UmHome=context.getInitParameter(CONTEXT_UM_HOME);         //wjh 2013
//		String urlstring = AvensConstants.UmHome + "getDutyPerson?condtype="
//				+ type + "&dn=" + orgid + "&limitedorg=" + orgid
//				+ "&condition=";
//		// String
//		// urlstring="http://192.168.1.213:8088/um/getDutyPerson?condtype="+type+"&dn="+orgid+"&limitedorg="+orgid;
//		String userstr = "";
//		try {
//			userstr = getpersonfromURL(urlstring);
//		} catch (MalformedURLException e) {
//			e.printStackTrace();
//		}
//		return userstr;
//	}
//
	static public String getAllDeptfromLdap() {

		String orgstr = null;
		//AvensConstants.BaseDN=	context.getInitParameter(CONTEXT_LOGIN_BASEDN);//wjh 2013
		//String orgId = AvensConstants.BaseDN.replaceAll("=", "%3D");  //wjh
		String orgId = Cfg.BaseDN.replaceAll("=", "%3D");  //wjh
		//String urlstring = AvensConstants.UmHome
		String urlstring = Cfg.UmHome
				+ "queryldapbin1?objectclass=guGongDepartment&basedn="
				+ orgId
				+ "&scope=2&amensearch=ou%3D*&receivemode=1&dnsplit=;&attrname=description,guGongDepSerial";
		// String
		// urlstring="http://192.168.1.207:8088/um/queryldapbin1?objectclass=guGongDepartment&basedn=dc%3Dgugong&scope=1&amensearch=ou%3D*&receivemode=1&dnsplit=;&attrname=description";
		try {
			orgstr = getpersonfromURL(urlstring);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return orgstr;
		// savetodb(userstr);

	}
//
//	// /////////////////////////////////////////////
//
//	private String getpropertyfromURL(String getpropertyurl)
//			throws MalformedURLException {
//		String s = null;
//		URL u = new URL(getpropertyurl);
//		DataInputStream din = null;
//		try {
//			// if (!u.getProtocol().equals("https"))
//			// throw new
//			// IOException("only 'https' URLs are valid for this method");
//			URLConnection uc = u.openConnection();
//			uc.setRequestProperty("Connection", "close");
//			try {
//				din = new DataInputStream(uc.getInputStream());
//				String temp = din.readUTF();
//				if (temp != null)
//					if (!temp.equals(""))
//						s = temp;
//			} catch (Exception ex) {
//				System.out.println("读流出错：" + ex);
//			}
//
//		} catch (Exception e) {
//			// out.println("验证出错："+e.getMessage());
//			// out.println("URL="+u.toString());
//		}
//
//		finally {
//			try {
//				if (din != null)
//					din.close();
//			} catch (IOException ex) {
//			}
//		}
//		return s;
//	}
//
//	
//	//wjh 2013
//	/*
//	 * 根据组织DN获取某一组织结构下的所有人，并以WfReource的形式表示
//	 */
////	public Set getResourceListFromLDAP(String orgdn) {
////		Set members = new LinkedHashSet();
////		// 从LDAP中获取某一组织结构下的所有人，并以WfReource的形式表示
////		// add by linhan
////		// queryldap?objectclass=guGongPerson&basedn=dc%3Dgugong&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;
////		String orgId = orgdn.replaceAll("=", "%3D");
////		String urlstring = AvensConstants.UmHome
////				+ "queryldapbin?objectclass=guGongPerson&basedn="
////				+ orgId
////				+ "&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;&jianzhi=1";
////		// String
////		// urlstring="http://192.168.1.66:8089/um/queryldap?objectclass=guGongPerson&basedn="+orgId+"&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;";
////		String result = "";
////		try {
////			result = getpropertyfromURL(urlstring);
////		} catch (MalformedURLException e) {
////			e.printStackTrace();
////		}
////		if (result != null && !result.equals("")) {
////			String[] arrReturn = null; // 返回值字符串数组
////			String strTemp = result;
////			int theIndex = 0;
////			int intCount = 0;
////			while (!strTemp.equals("") && strTemp != null) {
////				theIndex = strTemp.indexOf(";");
////				if (theIndex == -1) {
////					break;
////				}
////				intCount++;
////				strTemp = strTemp.substring(theIndex + 1);
////			}
////			arrReturn = new String[intCount];
////			String userid = "", usercn = "";
////			// 生成字符串数组
////			for (int i = 0; i < intCount; i++) {
////				theIndex = result.indexOf(";");
////				if (theIndex == -1) {
////					break;
////				}
////				arrReturn[i] = result.substring(0, theIndex);
////				result = result.substring(theIndex + 1);
////				WfResource res = null;
////				try {
////					// modify by linhan
////					int j = arrReturn[i].indexOf(",");
////					if (j > 0)
////						usercn = arrReturn[i].substring(0, j);
////					else
////						usercn = arrReturn[i];
////					userid = usercn.replaceAll("cn=", "");
////					// res
////					// =SharkEngineManager.getInstance().getResourceObject(arrReturn[i]);
////					res = AvensEngineManager.getInstance().getResourceObject(
////							userid);
////					// ///////////////////////
////				} catch (Exception ex) {
////				}
////				members.add(res);
////			}
////
////		}
////		//
////
////		return members;
////	}
//
//	public String getuserDnbyid(String userid) {
//
//		userid = "cn%3D" + userid;
//		String urlstring = AvensConstants.UmHome
//				+ "queryldapbin?objectclass=guGongPerson&basedn="
//				+ AvensConstants.BaseDN + "&scope=2&amensearch=" + userid
//				+ "&receivemode=1&dnsplit=;";
//		// String
//		// urlstring="http://192.168.1.66:8089/um/queryldap?objectclass=guGongPerson&basedn="+orgId+"&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;";
//		String result = "";
//		try {
//			result = getpropertyfromURL(urlstring);
//		} catch (MalformedURLException e) {
//			e.printStackTrace();
//		}
//		int i = result.indexOf(";");
//		if (i > 0)
//			result = result.substring(0, i);
//		return result;
//
//	}
//
//	public String getuserNamebyDn(String userdn) {
//
//		String UserURL = userdn.replaceAll("=", "%3D");
//		String urlstring = AvensConstants.getpropertyURL + "?dn=" + UserURL
//				+ "&attrlist=description&receivemode=1";
//		String result = "";
//		try {
//			result = getpropertyfromURL(urlstring);
//		} catch (MalformedURLException e) {
//			e.printStackTrace();
//		}
//		return result;
//
//	}
//	
//	
////wjh 2013
//	/*
//	 * 根据组织DN获取某一组织结构下的所有人，并以String的形式表示
//	 */
////	public String getResourceListStringFromLDAP(String orgdn) {
////		// 从LDAP中获取某一组织结构下的所有人，并以String的形式表示
////		// add by linhan
////		// queryldap?objectclass=guGongPerson&basedn=dc%3Dgugong&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;
////		String orgId = orgdn.replaceAll("=", "%3D");
////		String urlstring = AvensConstants.UmHome
////				+ "queryldapbin?objectclass=guGongPerson&basedn="
////				+ orgId
////				+ "&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;&jianzhi=1";
////		// String
////		// urlstring="http://192.168.1.66:8089/um/queryldap?objectclass=guGongPerson&basedn="+orgId+"&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;";
////		String result = "";
////		try {
////			result = getpropertyfromURL(urlstring);
////		} catch (MalformedURLException e) {
////			e.printStackTrace();
////		}
////
////		return result;
////	}
//
//	public String getorgDnbyid(String orgid) {
//
//		String OrgId = "ou%3D" + orgid;
//		String urlstring = AvensConstants.UmHome
//				+ "queryldapbin?objectclass=guGongDepartment&basedn="
//				+ AvensConstants.BaseDN + "&scope=2&amensearch=" + OrgId
//				+ "&receivemode=1&dnsplit=;";
//		// String
//		// urlstring="http://192.168.1.66:8089/um/queryldap?objectclass=guGongPerson&basedn="+orgId+"&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;";
//		String result = "";
//		try {
//			result = getpropertyfromURL(urlstring);
//		} catch (MalformedURLException e) {
//			e.printStackTrace();
//		}
//		int i = result.indexOf(";");
//		if (i > 0)
//			result = result.substring(0, i);
//		return result;
//
//	}
//
//	// ////////////////////
//	public Set getSameLevelResourceListFromLDAP(String org) {
//		Set members = new LinkedHashSet();
//		// TODO:从LDAP中获取某一组织结构下的所有人，并以WfReource的形式表示
//		// add by linhan
//		// queryldap?objectclass=guGongPerson&basedn=dc%3Dgugong&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;
//		String orgId = org.replaceAll("=", "%3D");
//		String urlstring = AvensConstants.UmHome
//				+ "queryldapbin?objectclass=guGongPerson&basedn="
//				+ orgId
//				+ "&scope=1&amensearch=cn%3D*&receivemode=1&dnsplit=;&jianzhi=1";
//		// String
//		// urlstring="http://192.168.1.66:8089/um/queryldap?objectclass=guGongPerson&basedn="+orgId+"&scope=2&amensearch=cn%3D*&receivemode=1&dnsplit=;";
//		String result = "";
//		try {
//			result = getpropertyfromURL(urlstring);
//		} catch (MalformedURLException e) {
//			// TODO 自动生成 catch 块
//			e.printStackTrace();
//		}
//		if (result != null && !result.equals("")) {
//			String[] arrReturn = null; // 返回值字符串数组
//			String strTemp = result;
//			int theIndex = 0;
//			int intCount = 0;
//			while (!strTemp.equals("") && strTemp != null) {
//				theIndex = strTemp.indexOf(";");
//				if (theIndex == -1) {
//					break;
//				}
//				intCount++;
//				strTemp = strTemp.substring(theIndex + 1);
//			}
//			arrReturn = new String[intCount];
//			String userid = "", usercn = "";
//			// 生成字符串数组
//			for (int i = 0; i < intCount; i++) {
//				theIndex = result.indexOf(";");
//				if (theIndex == -1) {
//					break;
//				}
//				arrReturn[i] = result.substring(0, theIndex);
//				result = result.substring(theIndex + 1);
//				WfResource res = null;
//				try {
//					// modify by linhan
//					int j = arrReturn[i].indexOf(",");
//					if (j > 0)
//						usercn = arrReturn[i].substring(0, j);
//					else
//						usercn = arrReturn[i];
//					userid = usercn.replaceAll("cn=", "");
//					// res
//					// =SharkEngineManager.getInstance().getResourceObject(arrReturn[i]);
//					res = AvensEngineManager.getInstance().getResourceObject(
//							userid);
//					// ///////////////////////
//				} catch (Exception ex) {
//				}
//				members.add(res);
//			}
//
//		}
//		//
//
//		return members;
//	}
//
//	public static void main(String[] args) {
//		SinosoftUM um = new SinosoftUM();
//		String result = um.getAllDeptfromLdap();
//		System.out.print("*****" + result);
//	}

}
